<template>
  <div class="todo-item">
    <input
      type="checkbox"
      :checked="props.todo.completed"
      @change="handleChange"
    />
    <input
      type="text"
      v-if="flag"
      @keyup.esc="handleEsc"
      @keyup.enter="handleUpdate"
      @blur="handleUpdate"
      :value="props.todo.content"
    />
    <label
      v-else
      @dblclick="props.todo.completed == 0 ? (flag = true) : (flag = false)"
      :class="props.todo.completed == 0 ? '' : 'item-label'"
      >{{ props.todo.content }}</label
    >
    <button @click="handleDelete"></button>
  </div>
</template>

<script setup>
import { ref } from "vue"
//定义数据
let flag = ref(false)
//接受父组件传过来的值
let props = defineProps({
  todo: {
    type: Object,
    required: true,
  },
})
//定义方法
const emit = defineEmits(["toggle", "delete", "update"])
//切换复选框状态
function handleChange() {
  emit("toggle", props.todo.id)
}
//删除
function handleDelete() {
  emit("delete", props.todo.id)
}
//更新
function handleUpdate(e) {
  if (flag.value == true) {
    emit("update", props.todo.id, e.target.value)
    flag.value = false
  }
}
//esc
function handleEsc() {
  flag.value = false
}
</script>

<style lang="stylus">
@import '../../../assets/styles/theme.styl'
@import '../../../assets/styles/mixins.styl'
.todo-item
  display: flex
  justify-content: space-between
  padding: 16px 16px 16px 10px
  border-bottom: 1px solid #C0C4CC
  // border-radius: 0 0 5px 5px
  font-size: 24px
  input[type='checkbox']
    //表单元素美化原则：去掉浏览器自带样式，使用自定义样式
    width: 40px
    height: 40px
    // color: $font
    clearDefault()
    //& 表示父元素
    &::after
      content: url('../../../assets/images/unChecked.svg')
    &:checked::after
      content: url('../../../assets/images/Checked.svg')
  input[type='text']
    flex: 1
    clearDefault()
    font-family: inherit
    color: $font
    font-size: 24px
    background-color: rgba(255,255,255,0.6)
    margin-left: 10px
    line-height: 40px
  label
    flex: 1
    color: $font
    line-height: 40px
    margin-left: 10px
    transition: all 0.4s
  button
    width: 40px
    height: 40px
    clearDefault()
    background-color: transparent
    cursor: pointer
  //& 表示 todo-item这个div，当 div hover时，给button添加伪元素
  &:hover
    button::after
      content: '×'
      font-size: 30px
      color: $skyblue
  .item-label
    text-decoration: line-through
    color: #999
</style>
